<template>
  <div class="myDiv">
    <div class="myDiv_header">
      <svg-icon icon-class="wk_upload_h" />
      <span v-if="upType == 41">上传超级查阅者</span>
      <span v-else-if="upType == 43">上传成员</span>
      <span v-else>上传管理员</span>
    </div>
    <div v-show="upType == 43">
      <!-- 上传成员 -->
      <el-table
        v-loading="loading"
        :data="pageData"
        show-summary
        :summary-method="getUpnum"
      >
        <el-table-column prop="userName" label="上传成员"> </el-table-column>
        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column prop="fileNum" label="上传份数"> </el-table-column>
        <el-table-column prop="uploaderEnable" label="上传权限">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.uploaderEnable"
              active-color="#F87A23"
              inactive-color="#D8D8D8"
              active-value="1"
              inactive-value="0"
              @change="changeUpEnable(scope.$index)"
            >
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部菜单栏 -->
      <div class="myDiv_bottom">
        <span class="left_text"
          >已上传{{ upNums }}份，还可上传{{ remainNum }}份</span
        >
        <div class="right_dc right_box" @click="payLoad">
          <el-button round>购买份数</el-button>
        </div>
        <div class="right_ac right_box" @click="openDrawer">
          <el-button round>添加人员</el-button>
        </div>
      </div>
    </div>
    <!-- 上传管理者和超级查阅者 -->
    <div v-show="upType == 42 || upType == 41">
      <!-- 上传管理员 -->
      <div class="up_manage" v-if="pageData.length > 0">
        <div
          class="up_manage_item flex"
          v-for="(item, index) in pageData"
          :key="item.userId"
        >
          <div class="item_left" @click="deleteRole(index)">
            <i class="el-icon-minus"></i>
          </div>
          <div class="flex item_right">
            <div class="header_img">
              <img :src="item.avatar || defaultAvatar" alt="" />
            </div>
            <span>{{ item.userName }}</span>
            <span class="m_r"
              >{{ item.phone }} | 已添加 {{ item.uploadNum }} 名上传成员</span
            >
          </div>
        </div>
      </div>
      <div class="noneData" v-else>暂无人员</div>
      <div class="myDiv_bottom upManages" @click="openDrawer">
        + {{ upType == 42 ? "添加上传管理员" : "添加超级查阅者" }}
      </div>
    </div>
    <!-- 添加抽屉 -->
    <Comdrawer
      @eventColse="showDrawer"
      :title="title"
      :drawer="drawer"
      :showClose="true"
    >
      <div class="p_30">
        <el-input
          v-if="inputType"
          placeholder="搜索分享者"
          ref="input"
          v-model="keyWord"
          @blur="inputType = false"
          prefix-icon="el-icon-search"
          class="search_in"
        >
        </el-input>
        <div class="search_box flex" @click="showInput" v-else>
          <i class="el-icon-search"></i>
          <span>搜索成员</span>
        </div>
        <!-- 分享者列表 -->
        <div class="person_list">
          <div
            class="person_list_item flex flex_js"
            v-for="item in personActiveList"
            :key="item.userId"
          >
            <div class="flex" :class="item.share ? 'opac' : ''">
              <div class="header">
                <el-image
                  class="header"
                  :src="item.avatar || defaultAvatar"
                ></el-image>
              </div>
              <div class="item_info">
                <div>{{ item.nickname }}</div>
                <span>{{ item.phonenumber }}</span>
              </div>
            </div>
            <!-- 选择按钮 -->

            <el-checkbox
              v-if="checkboxType"
              class="checkBox"
              v-model="item.value"
              :disabled="item.disabled"
              :checked="item.checked"
            ></el-checkbox>
          </div>
          <div class="footer flex flex_js">
            <h1>已选：{{ checkValue }}个</h1>
            <div class="submit" @click="submit">确认添加</div>
          </div>
        </div>
      </div>
    </Comdrawer>
  </div>
</template>

<script>
import {
  getMenbersApi,
  getFileboxRoleList,
  listCircleStaff,
  setRole,
  roleEdit,
  getFileSum,
  deleteRoleApi,
} from "@/BMViews/api/intelligentControl/intelligentControl.js";
import Comdrawer from "@/wss/components/Comdrawer.vue";
export default {
  name: "uploadCenter",
  components: { Comdrawer },
  props: ["upType", "circle_id", "circleInfo"],
  data() {
    return {
      type: 0, //传入类型判断
      pageData: [
        //上传人员data
      ],
      keyWord: "", //搜索关键词
      upNum: 0, //列表合计上传份数
      upNums: 0, //接口上传份数
      manageData: [],
      title: "", //抽屉顶部标题
      drawer: false, //添加人员
      roleID: "", //角色id
      personList: [], //可添加人员列表
      personActiveList: [], //展示的人员列表
      loading: false,
      inputType: false, //输入框状态
      checkboxType: false, //复选框绑定值强制刷新
      defaultAvatar: require("@/assets/images/defaultAvatar.jpg"),
    };
  },
  watch: {
    upType: {
      handler(newValue) {
        // this.getFileSum();
        switch (newValue) {
          case 41:
            this.getMenbersApi({
              fileboxId: this.circle_id,
              superReader: 1,
            });
            break;
          case 42:
            this.getMenbersApi({
              fileboxId: this.circle_id,
              uploadManager: 1,
            });

            break;
          case 43:
            this.getMenbersApi({
              fileboxId: this.circle_id,
              uploader: 1,
            });

            break;
        }
        this.checkboxType = false;
        this.getFileboxRoleList();
      },
    },
    keyWord: {
      handler(newValue) {
        if (newValue) {
          this.personActiveList = this.personList.filter((item) => {
            let strValue =
              item.nickname +
              JSON.parse(JSON.stringify(item.phonenumber)).replace(/\s*/g, "");
            return strValue?.indexOf(newValue.trim()) !== -1;
          });
        } else {
          this.personActiveList = JSON.parse(JSON.stringify(this.personList));
        }
      },
    },
  },
  computed: {
    checkValue() {
      let num = 0;
      this.personActiveList.forEach((item) => {
        if (item.value && !item.checked) {
          num += 1;
        }
      });
      return num;
    },
    remainNum() {
      return this.circleInfo.fileNum - this.upNums;
    },
  },
  methods: {
    // 关闭抽屉
    showDrawer() {
      this.drawer = !this.drawer;
    },
    getUpnum(param) {
      //上传成员合计显示显示的方法
      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (index === 2 && !values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          this.upNum = sums[index];
        } else {
          sums[index] = "--";
        }
      });

      return sums;
    },
    // 获取成员列表
    async getMenbersApi(e) {
      try {
        const res = await getMenbersApi(e);
        if (res.code == 200) {
          this.pageData = res.rows;
        }
      } catch (error) {}
    },
    // ---------------------上传人员
    // 获取个人id
    async getFileboxRoleList() {
      try {
        const res = await getFileboxRoleList({
          filebox_id: this.circle_id,
        });
        if (res.code == 200) {
          // this.roleID = res.rows[0].id
          this.listCircleStaff(res.rows[0].id);
        }
      } catch (error) {}
    },

    //获取可上传成员
    async listCircleStaff(e) {
      try {
        const res = await listCircleStaff({
          fileboxId: this.circle_id,
          fileId: e,
        });

        if (res.code == 200) {
          this.personList = res.rows;
          this.personActiveList = JSON.parse(JSON.stringify(res.rows));
        }
      } catch (error) {}
    },
    // 确认添加
    submit() {
      const that = this;
      let userIds = [];
      that.personActiveList.forEach((item) => {
        item.value && !item.disabled ? userIds.push(item.userId) : "";
      });
      if (userIds.length <= 0) {
        return;
      }
      let role = "super_reader";
      if (this.upType == 43) {
        role = "uploader";
      } else if (this.upType == 42) {
        role = "upload_manager";
      }
      // 调取api
      setRole({
        fileboxId: that.circle_id,
        role,
        userIds,
      }).then((res) => {
        that.personList.forEach((item) => {
          if (userIds.join("").indexOf(item.userId) != -1) {
            item.checked = true;
            item.disabled = true;
          }
        });
        that.personActiveList = JSON.parse(JSON.stringify(that.personList));
        if (res.code == 200) {
          that.$message({
            message: "操作成功",
            type: "success",
          });
          switch (that.upType) {
            case 41:
              that.getMenbersApi({
                fileboxId: that.circle_id,
                superReader: 1,
              });
              break;
            case 42:
              that.getMenbersApi({
                fileboxId: that.circle_id,
                uploadManager: 1,
              });
              break;
            case 43:
              that.getMenbersApi({
                fileboxId: that.circle_id,
                uploader: 1,
              });
              break;
          }
        }
      });
    },
    // 切换权限
    async changeUpEnable(e) {
      this.loading = !this.loading;
      const res = await roleEdit({
        id: this.pageData[e].id,
        uploaderEnable: this.pageData[e].uploaderEnable,
      });
      if (res.code == 200) {
        this.loading = !this.loading;
      }
    },
    // 购买份数，跳转收银台
    payLoad() {
      this.$emit("payLoad");
    },
    // 获取已上传份数
    async getFileSum() {
      const res = await getFileSum({
        fileboxId: this.circle_id,
      });
      if (res.code == 200) {
        this.upNums = res.data;
      }
    },
    // 点击搜索框，获取焦点
    showInput() {
      this.inputType = true;

      this.$nextTick(() => {
        this.$refs.input.focus();
      });
    },
    // -----------------------上传管理员
    // 添加上传管理员
    openDrawer() {
      if (this.upType == 43) {
        this.title = "添加上传人员";
      } else if (this.upType == 42) {
        this.title = "添加上传管理员";
      } else {
        this.title = "添加超级查阅者";
      }

      for (let i in this.pageData) {
        this.personList.forEach((item) => {
          if (this.pageData[i].userId == item.userId) {
            item.disabled = true;
            item.checked = true;
            item.value = true;
          }
        });
      }
      this.personActiveList = JSON.parse(JSON.stringify(this.personList));

      this.checkboxType = true;
      this.drawer = !this.drawer;
     
    },
    // 删除弹框
    deleteRole(e) {
      this.$confirm("确认要删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "message",
      })
        .then(() => {
          this.deleteRoleApi(e);
        })
        .catch((err) => {});
    },
    async deleteRoleApi(e) {
      let data;
      if (this.upType == 42) {
        data = {
          id: this.pageData[e].id,
          uploadManager: 0,
        };
      } else if (this.upType == 41) {
        data = {
          id: this.pageData[e].id,
          superReader: 0,
        };
      }

      const res = await deleteRoleApi(data);
      if (res.code == 200) {
        this.$message({
          message: "删除成功",
        });

        this.personList.forEach((item) => {
          if (this.pageData[e].userId == item.userId) {
            item.checked = false;
            item.disabled = false;
            item.value = false;
          }
        });

        this.personActiveList = JSON.parse(JSON.stringify(this.personList));

        this.pageData.splice(e, 1);
      }
    },
  },
  created() {},
  mounted() {
    this.getFileSum();
    switch (this.upType) {
      case 41:
        break;
      case 42:
        this.getMenbersApi({
          fileboxId: this.circle_id,
          uploadManager: 1,
        });

        break;
      case 43:
        this.getMenbersApi({
          fileboxId: this.circle_id,
          uploader: 1,
        });

        break;
    }
    this.getFileboxRoleList();
  },
  beforeUpdate() {},
};
</script>
<style lang="scss" scoped>
.message {
  z-index: 2999;
}
.flex {
  display: flex;
  align-items: center;
}

.flex_js {
  justify-content: space-between;
}
.flex_fe {
  justify-content: flex-end;
}
.border_b {
  border-bottom: 1px solid #efefef;
}
.m_r_10 {
  margin-right: 10px;
}
.gray {
  color: #999999;
}
::v-deep .person_list_item .el-checkbox__inner {
  border-radius: 50%;
}
::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after {
  border-color: #fff;
}
::v-deep .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
  background-color: #e6e6e6;
  opacity: 0.3;
}
::v-deep .input_box .el-input__inner {
  width: 300px;
  padding: 0;
  margin-left: 15px;
  height: 38px;
  border: none;
}
::v-deep .footer .el-textarea__inner {
  resize: none;
  border: none;
}
::v-deep .el-input--medium .el-input__inner {
  border-radius: 20px !important;
}
.opac {
  opacity: 0.3;
}
.p_30 {
  padding: 0 30px;

  .search_box {
    width: 100%;
    height: 36px;
    background: #ffffff;
    border-radius: 20px;
    border: 1px solid #c4c6ca;
    justify-content: center;
    &:hover {
      background-color: #e8f4ff;
    }
    i {
      margin-right: 7px;
      color: #cccccc;
    }
    span {
      font-size: 12px;
      color: #cccccc;
    }
  }
  .person_list {
    .person_list_item {
      width: 100%;
      height: 70px;
      border-bottom: 1px solid #efefef;

      .header {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: gray;
        margin-right: 12px;
      }
      .item_info {
        font-size: 14px;
        color: #232323;
        div {
          margin-bottom: 3px;
        }
        span {
          color: #999999;
          font-size: 12px;
        }
      }
      .checkBox {
        transform: scale(1.5);
      }
    }
  }
  // 抽屉底部样式
  .footer {
    position: absolute;
    bottom: 0;
    left: 0;
    height: 80px;
    width: 100%;
    padding: 0 30px;
    border-top: 1px solid #ecedf0;

    .submit {
      width: 110px;
      height: 40px;
      background: #f87a23;
      border-radius: 20px;
      text-align: center;
      line-height: 40px;
      font-size: 14px;
      color: #fff;
    }
  }
}
.myDiv {
  position: relative;
  height: 100%;
  background: #ffffff;
  border-radius: 12px;
  border: 1px solid #ecedf0;
  padding: 0 32px;
  .myDiv_header {
    display: flex;
    align-items: center;
    height: 86px;
    border-bottom: 1px solid #efefef;
    span {
      font-size: 24px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #333333;
      margin-left: 13px;
    }
  }
  .myDiv_bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    width: 100%;
    height: 45px;
    padding: 0 30px;
    border-radius: 0px 0px 12px 12px;
    border-top: 1px solid #ecedf0;
    overflow: hidden;
    box-sizing: border-box;
    .left_text {
      font-size: 14px;
      color: #333333;
      font-family: PingFangSC-Regular, PingFang SC;
    }
    .right_box {
      width: 115px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
    
    }
    .right_ac {
      ::v-deep .el-button {
        border: 1px solid #f87a23;
        background-color: #f87a23;
        color: #fff;
      }
    }
    .right_dc {
      margin: 0 10px 0 auto;
      ::v-deep .el-button {
        border: 1px solid #f87a23;
        color: #f87a23;
      }
    }
  }
  // 上传管理员内容
  .up_manage {
    width: 100%;
    .up_manage_item {
      justify-content: space-between;
      .item_left {
        width: 14px;
        height: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #909aaa;
        color: #fff;
        border-radius: 50%;
        box-sizing: border-box;
        margin-right: 16px;
      }
      .item_right {
        flex: 1;
        line-height: 66px;
        border-bottom: 1px solid #efefef;
        font-size: 14px;
        .header_img {
          width: 36px;
          height: 36px;
          margin-right: 10px;
          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }
        }
      }
      .m_r {
        margin-left: auto;
        color: #999999;
        font-size: 12px;
      }
    }
  }
  // 上传管理员底部
  .upManages {
    justify-content: center;
    background-color: #f8f8f8;
    border-radius: 0 0 0 12px;
    border: 1px solid #ecedf0;
    color: #606e84;
    font-size: 14px;
  }
}
.noneData {
  font-size: 22px;
  text-align: center;
  line-height: 100px;
}
</style>